<script setup lang="ts">
import { computed, ref } from 'vue';
import type { VNode } from 'vue';
import { useAuthStore } from '@/store/modules/auth';
import { useRouterPush } from '@/hooks/common/router';
import { useSvgIcon } from '@/hooks/common/icon';
import { $t } from '@/locales';
import ChangePasswordDialog from './change-password-dialog.vue';

defineOptions({ name: 'UserAvatar' });

const authStore = useAuthStore();
const { routerPushByKey, toLogin } = useRouterPush();
const { SvgIconVNode } = useSvgIcon();

function loginOrRegister() {
  toLogin();
}

type DropdownKey = 'user-center' | 'change-password' | 'logout';

type DropdownOption = {
  key: DropdownKey;
  label: string;
  icon?: () => VNode;
};

const SHOWCHANGEPWD = import.meta.env.VITE_SHOW_CHANGEPWD === 'Y';

const options = computed(() => {
  const opts: DropdownOption[] = [
    {
      label: $t('common.logout'),
      key: 'logout',
      icon: SvgIconVNode({ icon: 'ep:failed', fontSize: 18 })
    }
  ];

  if (SHOWCHANGEPWD) {
    opts.unshift({
      label: '修改密码',
      key: 'change-password',
      icon: SvgIconVNode({ icon: 'ep:lock', fontSize: 18 })
    });
  }

  return opts;
});

function logout() {
  window.$messageBox
    ?.confirm($t('common.logoutConfirm'), $t('common.tip'), {
      confirmButtonText: $t('common.confirm'),
      cancelButtonText: $t('common.cancel'),
      type: 'warning'
    })
    .then(() => {
      authStore.resetStore();
    });
}

// 修改密码弹框显示状态
const showChangePasswordDialog = ref(false);

function handleDropdown(key: DropdownKey) {
  if (key === 'logout') {
    logout();
  } else if (key === 'change-password') {
    showChangePasswordDialog.value = true;
  } else {
    // If your other options are jumps from other routes, they will be directly supported here
    routerPushByKey(key);
  }
}

function handleChangePasswordSuccess() {
  window.$message?.success('密码修改成功');
}
</script>

<template>
  <ElButton v-if="!authStore.isLogin" text @click="loginOrRegister">
    {{ $t('page.login.common.loginOrRegister') }}
  </ElButton>

  <ElDropdown trigger="click" @command="handleDropdown">
    <template #dropdown>
      <ElDropdownMenu>
        <ElDropdownItem
          v-for="{ key, label, icon } in options"
          :key="key"
          class="mx-4px my-1px rounded-6px"
          :icon="icon"
          :command="key"
        >
          {{ label }}
        </ElDropdownItem>
      </ElDropdownMenu>
    </template>
    <div class="flex items-center">
      <SvgIcon icon="ep:user" class="mr-5px text-icon-large" />
      <span class="text-16px font-medium">{{ authStore.userInfo.name }}</span>
    </div>
  </ElDropdown>

  <!-- 修改密码弹框 -->
  <ChangePasswordDialog v-model:visible="showChangePasswordDialog" @success="handleChangePasswordSuccess" />
</template>

<style scoped></style>
